<script lang="ts" setup>
import { ref, reactive, watch, computed } from "vue"
import { CirclePlus, RefreshRight, Search, Refresh } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { formatDateTime } from "@/utils"

import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus"
import { addMsgTmp, seeMsgTmp, editMsgTmp, delMsgTmp } from "@/api/msg"
defineOptions({
  name: "MsgTmp"
})
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const loading = ref<boolean>(false)
//#region 增
const dialogVisible = ref<boolean>(false)
const formData = reactive<any>({
  temType: 1,
  temName: "",
  temContent: "",
  remark: "",
  signName: "",
  paramJson: null
})
const formRules: FormRules = reactive({
  temType: [{ required: true, trigger: "change", message: "请选择模板类型" }],
  signName: [{ required: true, trigger: "change", message: "请选择短信签名" }],
  temName: [{ required: true, trigger: "blur", message: "请输入模板名字" }],
  temContent: [{ required: true, trigger: "blur", message: "请输入模板内容" }]
})
//选择签名插入模板
const baseString = ref("")
const formattedString = computed(() => {
  return formData.temType != 3
    ? baseString.value.replace("", formData.temContent).replace("", formData.signName)
    : baseString.value.replace("", formData.temContent).replace("", formData.signName) + "，拒收请回复R"
})

//#endregion
//模板类型切换清除模板内容
const changeFlag = ref<any>("")
const temTypeChange = () => {
  ElMessageBox.confirm(`切换模板类型将清空模板相关内容,确定切换吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      varSel.value = ""
      variable.value = ""
      formData.temContent = ""
      formData.signName = ""
      formData.temName = ""
      formData.remark = ""
      formData.paramJson = null
    })
    .catch(() => {
      console.log("cancle")
      formData.temType = changeFlag.value
    })
}

//根据模板内容动态展示变量相关
const variable = ref("")
const varSel = ref("")
const selVal = ref([
  { k: "手机号", v: "mobile_number" },
  { k: "其他号码", v: "other_number" },
  { k: "金额", v: "amount" },
  { k: "日期", v: "date" },
  { k: "中文", v: "chinese" },
  { k: "其他", v: "others" }
])
const arrObj = ref<any>({
  keys: [],
  values: []
})
const keyInput = (val: any) => {
  arrObj.value.keys = val.match(/{([\u4e00-\u9fa5a-zA-Z0-9]+)}/g)
    ? val.match(/{([\u4e00-\u9fa5a-zA-Z0-9]+)}/g).map(function (match: any) {
        return match.slice(1, -1)
      })
    : []
  if (arrObj.value.keys && arrObj.value.keys[0] && formData.temType != 3) {
    try {
      variable.value = arrObj.value.keys[0]
      formData.paramJson = {
        [variable.value]: varSel
      }
      console.log(formData.paramJson)
      if (arrObj.value.keys.length > 1 && formData.temType == 1) {
        ElMessage.error("验证码类型的参数只能添加一个，不能重复添加！")
      }
    } catch (error) {
      console.log(error)
    }
  } else {
    variable.value = ""
    formData.paramJson = null
  }
}

const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        // console.log(arrObj.value)
        if (formData.temType == 2) {
          formData.paramJson = arrObj.value.keys.reduce((acc: any, curr: any, index: any) => {
            acc[curr] = arrObj.value.values[index]
            return acc
          }, {})
        }

        addMsgTmp({
          temType: formData.temType,
          temName: formData.temName,
          remark: formData.remark,
          temContent: formattedString.value,
          paramJson: formData.paramJson
        }).then((res: any) => {
          ElMessage.success(res.data)
          dialogVisible.value = false
          getTableData()
        })
      } else {
        if (formData.temType == 2) {
          formData.paramJson = arrObj.value.keys.reduce((acc: any, curr: any, index: any) => {
            acc[curr] = arrObj.value.values[index]
            return acc
          }, {})
        }
        editMsgTmp({
          temId: currentUpdateId.value,
          temType: formData.temType,
          temName: formData.temName,
          remark: formData.remark,
          temContent: formattedString.value,
          paramJson: formData.paramJson
        }).then((res: any) => {
          ElMessage.success(res.data)
          dialogVisible.value = false
          getTableData()
        })
      }
    } else {
      return false
    }
  })
}
//#endregion

//#region 删
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除此模板？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delMsgTmp(row.temId).then(() => {
      // ElMessage.success("删除成功")
      getTableData()
    })
  })
}

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  dialogVisible.value = true
  currentUpdateId.value = row.temId
  formData.temName = row.temName
  formData.remark = row.remark
  formData.temType = row.temType
  formData.paramJson = row?.paramJson
  arrObj.value.keys = []
  arrObj.value.values = []
  if (formData.paramJson) {
    Object.keys(formData.paramJson).forEach((key) => {
      // console.log(key, formData.paramJson[key]) // 输出对象的键值对
      if (row.temType == 1) {
        variable.value = key
        varSel.value = formData.paramJson[key]
      } else if (row.temType == 2) {
        arrObj.value.keys.push(key)
        arrObj.value.values.push(formData.paramJson[key])
      } else {
        arrObj.value.keys = []
        arrObj.value.values = []
        variable.value = ""
        varSel.value = ""
      }
    })
  }
  formData.temContent = row.temContent.replace(/【(.*?)】/g, "").replace("，拒收请回复R", "")
  if (row.temContent.match(/【(.*?)】/)) {
    formData.signName = row.temContent.match(/【(.*?)】/)[0]
  }
}
//#endregion

// #region 搜索
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  temName: "" // 套餐ID
})
// 查询按键
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}

// 重置按键
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}

//#region 查
const tableData = ref<any>([])
const getTableData = () => {
  loading.value = true
  seeMsgTmp({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    temName: searchData.temName
    // package_id: searchData.package_id
  })
    .then((res: any) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
      console.log(res, "查询的数据")
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
import { seeMsgSign } from "@/api/msg"
const singnList = ref<any>([])

const getSignList = () => {
  seeMsgSign({
    page: 1,
    size: 1000,
    auditResult: "2"
    // package_id: searchData.package_id
  })
    .then((res: any) => {
      singnList.value = res.data.list
    })
    .catch(() => {
      singnList.value = []
    })
}
getSignList()

// 刷新数据
const handleRefresh = () => {
  getTableData()
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
//#endregion

watch([() => formData.temType], (n, o) => {
  // console.log(n)
  changeFlag.value = o[0]
  // if (!changeFlag.value) {
  //   formData.temType = o
  // } else {
  //   formData.temType = n
  // }
})

// #region 清除验证  清除规则报错信息
const formRef = ref<FormInstance | null>(null)
const clearValidateA = () => {
  formRef.value?.clearValidate()
  formRef.value?.resetFields()
}
const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidateA()
  varSel.value = ""
  variable.value = ""
  // 清空reactive对象里面的key值
  Object.keys(formData).map((key) => {
    delete formData[key]
  })
  formData.temType = 1
}
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="temName" label="模板">
          <el-input v-model.trim="searchData.temName" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">创建模板</el-button>
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column prop="temId" label="模板ID" align="center" />
          <el-table-column prop="createTime" label="申请时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="temName" label="模板名称" align="center" />
          <el-table-column prop="temContent" label="模板内容" align="center" />
          <!-- <el-table-column prop="sign_name" label="字数" align="center" /> -->
          <el-table-column label="审核状态" align="center">
            <template #default="scope">
              <span v-if="scope.row.auditResult == 1">待审核</span>
              <span v-if="scope.row.auditResult == 2">审核通过</span>
              <span v-if="scope.row.auditResult == 3"
                >审核不通过<span v-if="scope.row.auditMsg" style="color: red">({{ scope.row.auditMsg }})</span></span
              >
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row)"
                :disabled="scope.row.auditResult == 2"
                >修改</el-button
              >
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增 修改 -->
    <el-dialog
      class="inputdialog"
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增' : '修改'"
      @close="resetForm"
      width="60%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="temType" label="模板类型">
          <el-radio-group v-model="formData.temType" class="ml-4" @change="temTypeChange">
            <el-radio :label="1" size="large"
              >验证码：适用于注册、登录、找回密码、身份验证、号码绑定身份验证的短信模板</el-radio
            >
            <el-radio :label="2" size="large"
              >行业通知：可发告知类短信，例如：快递通知、消费通知、账单、服务通知</el-radio
            >
            <el-radio :label="3" size="large">会员营销：可用于会员服务，内容可带链接，建议转换成短链接发送。</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="temName" label="模板名称">
          <el-input v-model="formData.temName" placeholder="签名限制20个字" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item prop="signName" label="短信签名">
          <el-select style="width: 100%" v-model="formData.signName" clearable filterable placeholder="请选择签名">
            <el-option v-for="item in singnList" :key="item.id" :label="item.sign" :value="item.sign" />
          </el-select>
        </el-form-item>
        <el-form-item prop="temContent" label="模板内容">
          <el-input
            v-model="formData.temContent"
            placeholder="请输入内容800字以内 ，如需要变量例如：{name}"
            maxlength="800"
            show-word-limit
            type="textarea"
            @input="keyInput"
            @change="keyInput"
          />
        </el-form-item>
        <el-form-item prop="var" label="已选变量" v-if="formData.paramJson">
          <div v-if="formData.temType == 1">
            <el-input v-model="variable" disabled style="width: 50%" />
            <el-select style="width: 50%" v-model="varSel" clearable filterable placeholder="请选择">
              <el-option :key="1" label="验证码" value="valid_code" />
            </el-select>
          </div>
          <template v-if="formData.temType == 2">
            <div v-for="(item, index) in arrObj.keys" :key="item" style="margin-right: 10px; margin-bottom: 10px">
              <el-input v-model="arrObj.keys[index]" disabled style="width: 50%" />
              <el-select style="width: 50%" v-model="arrObj.values[index]" clearable filterable placeholder="请选择">
                <el-option v-for="subItem in selVal" :key="subItem.v" :label="subItem.k" :value="subItem.v" />
              </el-select>
            </div>
          </template>
        </el-form-item>
        <el-form-item prop="remark" label="申请说明">
          <el-input v-model="formData.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">提交审核</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.Signature-matter {
  margin-bottom: 20px;
  border: 1px solid #6cf;
  background: #e5f0ff;
  padding: 10px 14px;
  border-radius: 5px;
  font-size: 12px;
}
:deep(.el-radio-group) {
  display: block;
}
:deep(.el-radio.el-radio--large) {
  display: block !important;
}
</style>
